<template>
  <div class="after-dispatch">
    <div style="display: flex; justify-content: space-between">
      <div></div>

      <div>
		  <el-select v-model="userId" filterable remote clearable
			placeholder="按名字或工号搜索" :loading="selectLoading"
		  	@change="getAllGoods" :remote-method="getUserList" 
			@focus="getUserList('')">
		  	<el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
		  	</el-option>
		  </el-select>
		  <!-- <el-button type="success" @click="receiptsStatusSelect">查询</el-button> -->
      </div>
    </div>

    <div class="goods-table">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        height="100%"
      >
	  <el-table-column prop="i" label="序号" fixed="left" width="50">
	  </el-table-column>
        <el-table-column prop="sn" label="订单流水号" width="130">
        </el-table-column>
        <el-table-column prop="userName" label="客户名称" width="80">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="115">
        </el-table-column>
		<el-table-column label="产品列表" width="80" v-if="userInfo.roleId !== 6">
			<template slot-scope="scope">
				<el-button type="text" @click="partsOpen(scope.row)">点击查看</el-button>
			</template>
		</el-table-column>
<!-- 		<el-table-column prop="partName" label="产品名称" width="140">
		</el-table-column>
        <el-table-column prop="ksModel" label="产品型号" width="140">
        </el-table-column> -->
        <el-table-column prop="serviceFrequency" label="服务次数" width="80">
        </el-table-column>
        <el-table-column prop="installationTime" label="安装时间" width="170">
          <!-- 格式化时间 -->
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.installationTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="afterSalesTime" label="订单派单时间" width="170">
          <!-- 格式化时间 -->
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.afterSalesTime) }}</span>
          </template>
        </el-table-column>
		<el-table-column prop="training" label="培训内容" fit>
			<template slot-scope="scope">
				<div style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
					{{scope.row.training}}
				</div>
			</template>
		</el-table-column>
        <!-- 进行中 未开始 已结束 -->
        <!-- <el-table-column prop="saleState" label="状态" fit width="100">
                    <template slot-scope="scope">
                        
                        <el-tag type="success"></el-tag>
                    </template>
                </el-table-column> -->
        <el-table-column prop="userId" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="Employeeupda(scope.row.afterSalesId)" type="text">
				编辑
			</el-button>
			<el-divider direction="vertical"></el-divider>
            <el-button size="mini" @click="applyUpdateEmployee(scope.row.afterSalesId)" type="text">
				交流记录
			</el-button>
			<el-divider direction="vertical"></el-divider>
            <el-button size="mini" @click="addAfterInfo(scope.row.afterSalesId)" type="text">
				添加记录
			</el-button>
<!--            <el-button v-if="roleType" size="mini" type="danger" type="text"
				@click="deleteGoods(scope.row)">
				删除
			</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background :current-page="currentPage" :page-size="pageSize"
			:total="total" :page-sizes="[20, 50, 100]" 
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </div>
	
	<!-- 查看产品列表弹窗 -->
	<el-dialog style="margin-top:0" :visible.sync="partsShow" width="75%" 
		title="产品列表" @close="partsClose">
		<div class="data-table">
			<el-table :data="selectData.goodsList" border stripe style="width: 100%" :max-height="500">
				<el-table-column prop="i" fixed="left" label="序号" width="50">
				</el-table-column>
				<el-table-column label="图片" width="120">
					<template slot-scope="scope">
							<el-image :src="READ_IMG_URL+scope.row.image" style="width: 90px; height: 90px;"
							:preview-src-list="new Array(READ_IMG_URL+scope.row.image)">
							</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="partName" label="零件名称" fit>
				</el-table-column>
				<el-table-column prop="model" label="零件型号" fit>
				</el-table-column>
				<el-table-column prop="devicesDescribe" label="产品描述" fit>
				</el-table-column>
				<el-table-column prop="remark" label="备注" fit>
				</el-table-column>
				<el-table-column prop="price" label="销售单价" width="100"
					v-if="userInfo.roleId === '1'">
				</el-table-column>
				<el-table-column prop="goodsCount" label="卖出数量" width="100">
				</el-table-column>
				<el-table-column prop="totalAmount" label="总计" width="100"
					v-if="userInfo.roleId === '1'">
				</el-table-column>
			</el-table>
		</div>
	</el-dialog>
	
    <!-- 交流内容 -->
    <el-dialog title="交流内容" :visible.sync="addFromDialog2" width="40%">
      <el-form
        :model="prudproducts"
        :inline="true"
        ref="prudproducts"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div style="display: flex; flex-wrap: wrap">
          <el-button
            v-for="(init, index) in afterSalesVoList"
            :key="init.id"
            type="success"
            style="width: 165px; margin-right: 10px; margin-bottom: 10px"
            plain
            @click="exchange(index)">
            {{ formatDate(init.afterTime) }}
          </el-button>
        </div>

        <div v-show="reminderTime != null">
          下次交流提醒时间：{{ formatDate(reminderTime) }}
        </div>
        <el-input
          style="margin-top: 20px"
          type="textarea"
          :autosize="{ minRows: 8, maxRows: 12 }"
          placeholder="这是交流内容"
          v-model="textarea2"
        >
        </el-input>
      </el-form>
    </el-dialog>

    <!-- 添加交流内容 -->
    <el-dialog title="添加交流记录" :visible.sync="addFromDialog3" width="40%">
      <el-form :model="addExchanges" :inline="true" ref="addExchanges"
        label-width="100px" class="demo-ruleForm">
        <div>下次交流提醒时间：</div>
        <br />
        <el-form-item prop="reminderTime">
          <el-date-picker v-model="addExchanges.reminderTime"
            type="datetime" placeholder="提醒时间">
		  </el-date-picker>
        </el-form-item>
        <!-- 交流内容 -->
        <br />
		<span>交流内容：</span>
        <el-input style="margin-top: 20px" type="textarea" 
			:autosize="{ minRows: 8, maxRows: 12 }" placeholder="这是交流内容"
			v-model="addExchanges.afterCount">
        </el-input>
      </el-form>
	  <div slot="footer">
	    <el-button type="primary" style="margin-top: 20px; margin-left: 20px"
	      @click="submitaddEmployeeForm" v-debounce>
	  	  提 交
	    </el-button>
	    <el-button type="danger" style="margin-top: 20px; margin-left: 20px"
	      @click="addFromDialog3 = false">
	  	  取 消
	    </el-button>
	  </div>
    </el-dialog>

    <!-- 新增产品 -->
    <el-dialog title="编辑信息" :visible.sync="addFromDialog" width="30%">
      <!-- 培训内容 -->
      <el-form :model="prudproducts" :inline="true" ref="prudproducts"
        label-width="100px" class="demo-ruleForm">
        <div>安装时间:</div>
        <el-form-item prop="installationTime" style="margin-top: 10px">
          <el-date-picker
            v-model="addExchanges2.installationTime"
            type="datetime"
            placeholder="安装时间"
          ></el-date-picker>
        </el-form-item>

        <div>培训内容:</div>
        <el-input style="margin-top: 20px" type="textarea" placeholder="培训内容"
			:autosize="{ minRows: 6, maxRows: 10 }" v-model="addExchanges2.training">
        </el-input>
      </el-form>
	  <!-- 保存和取消的按钮 -->
	  <div slot="footer">
	  	<el-button type="primary" @click="submitaddEmployeeForm2" v-debounce>
	  		保 存
	  	</el-button>
	  	<el-button type="danger" @click="addFromDialog = false">
	  		取 消
	  	</el-button>
	  </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
import {
  addEmployeeProfile,
  selectEmployeeProfileByName,
  devicesSelectList, //查询仓库产品列表
  afterDispatch, //查询当前售后人员的派单记录, 分页
  selectExchange, //查询交流记录
  addExchange, //添加交流记录
  updateInstall, //修改安装时间,培训内容
} from "../../api/all";
import afterSalesApi from "../../api/afterSales.js";
import userApi from "../../api/user.js";
import config from '../../api/apiURL.js';
export default {
  components: {},
  data() {
    return {
		READ_IMG_URL: config.READ_IMG_URL,
		selectLoading: false,
		userList: [],
		userId: null,
		userInfo: {},
		receiptsStatusValue: '',
		receiptsStatusList: [],
		receiptsStatusSelect: '',
      //安装和培训内容
      addExchanges2: {
        afterSalesId: "",
        installationTime: "",
        training: "",
      },

      //提交该售后订单的交流记录
      addExchanges: {
        afterSalesId: "", //售后订单id
        afterCount: "", //交流内容
        reminderTime: "", //下次交流提醒时间
      },
      //下次提醒时间
      reminderTime: null,
      //交流列表
      afterSalesVoList: [],
      //搜索框的值
      input: "",
      //这是用户交流次数显示的地方
      textarea2: "",
      // 图片预览
      srcList: [],
      srcList2: [],
      //新增标题
      title: "新增产品",
      roleType: false,
      cover: "cover",
      // 显示表单
      addFromDialog: false,
      addFromDialog2: false,
      addFromDialog3: false,
      // 表格加载
      loading: false,
      //合同到期提醒
      dialogImageUrl: "",
      dialogVisible: false,
      //新增采购表格数据
      prudproducts: {
        suppliersId: "", //供应商id
        productsId: "", //产品id
        productsName: "", //产品名称
        description: "", //产品描述
        price: "", //产品价格
        model: "", //产品型号
        isIncludingTax: "", //是否含税
        number: "", //产品数量
        image: "", //产品图片
        purchaser: "", //采购人
        storageTime: "", //入库时间
        paymentType: "", //结款方式 (1现金,2月结)
        status: "", //入库状态 （0已通过，1待审核,2审核失败）
      },
      tableData: [],
      //总数页
      total: 1,
      // 分页大小
      pageSize: 50,
      //记录当前页数
      currentPage: 1,
      //审核通过状态
      applyStatus: false,
	  partsShow: false,
	  selectTitle: '',
	  selectData: {}
    };
  },
  mounted() {
    let kes = window.sessionStorage.getItem("loginUser");
    this.userInfo = JSON.parse(kes);
    if (this.userInfo.roleType == "root") {
      this.roleType = true;
    }
    this.getAllGoods();
    // console.log("初始化时间:", dayjs())
    //通过入库名称搜索框查询
    // this.list = this.states.map((item) => {
    //   return { value: `value:${item}`, label: `label:${item}` };
    // });
  },
  //超级管理员显示功能
  methods: {
    // 格式化时间
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      const hours = d.getHours().toString().padStart(2, "0");
      const minutes = d.getMinutes().toString().padStart(2, "0");
      const seconds = d.getSeconds().toString().padStart(2, "0");
      if (date == null) {
        return "未设置时间";
      }
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      // return `${year}-${month}-${day}`;
    },
    startTimeChange(value) {
      this.addEmployeeForm.startTime = dayjs(value).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    endTimeChange(value) {
      this.addEmployeeForm.endTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },

    //点击编辑
    Employeeupda(id) {
      //判断是否有安装时间和培训内容
      console.log(this.tableData);
      for (const item of this.tableData) {
        if (item.afterSalesId == id) {
          if (item.installationTime != null || item.training != null) {
            this.addExchanges2.installationTime = item.installationTime;
            this.addExchanges2.training = item.training;
          }
        }
      }
      this.addExchanges2.afterSalesId = id;
      this.addFromDialog = true;
      this.title = "编辑产品";
      this.addEmployeeForm = this.tableData.find((item) => item.id === id);
      this.imgstatus();
    },

    //点击交流时间
    exchange(index) {
      this.textarea2 = this.afterSalesVoList[index].afterCount;
    },

    //点击添加记录
    addAfterInfo(i) {
      this.addExchanges.afterSalesId = i;
      this.addFromDialog3 = true;
    },

    //点击交流记录
    applyUpdateEmployee(id) {
      selectExchange(id).then((data) => {
        if (data.code == 200) {
          this.afterSalesVoList = data.data;
          if (this.afterSalesVoList.length <= 0 || data.data[0] == null) {
            this.reminderTime = null;
            this.textarea2 = "";
          } else {
            this.reminderTime = data.data[0].reminderTime;
            this.textarea2 = data.data[0].afterCount;
          }
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
      this.addFromDialog2 = true;
    },
    // 新增交流记录
    submitaddEmployeeForm() {
      //表单校验
      if (
        this.addExchanges.reminderTime == null ||
        this.addExchanges.afterCount == ""
      ) {
        this.$message({
          type: "error",
          message: "请填写完整内容再提交",
        });
        return;
      }
      addExchange(this.addExchanges).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: data.message,
          });
          this.addFromDialog3 = false;
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },

    //保存编辑的信息
    submitaddEmployeeForm2() {
      if (
        this.addExchanges2.installationTime == "" ||
        this.addExchanges2.training == ""
      ) {
        this.$message({
          type: "error",
          message: "请填写完整内容再提交",
        });
        return;
      }
      updateInstall(this.addExchanges2).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: data.message,
          });
          this.addFromDialog = false;
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },

    //模糊查询信息
    likeEmployee() {
      selectEmployeeProfileByName(this.input).then((data) => {
        if (data.code) {
          this.tableData = data.data.map((item,index) =>{
			  item.i = index+1;
			  return item;
		  });
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },

    //初始化图片
    imgstatus() {
      let url =
        "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
      this.imageUrl = url;
      this.imageUrl2 = url;
    },

    // 查询列表
    getAllGoods() {
      this.loading = true;
	  const data = {
		  userId: this.userId,
		  currentPage: this.currentPage,
		  pageSize: this.pageSize
	  }
	  afterSalesApi.getAfterSaleList(data).then(res =>{
		  if (res.code === 200){
			  this.total = res.data.total;
			  this.tableData = res.data.afterSalesVoList.map((item,index) =>{
			  	item.i = (this.currentPage - 1) * this.pageSize + index + 1;
			  	return item;
			  });
		  }
	  }).finally(() =>{
		  this.loading = false;
	  })
      // getGoodsList(this.currentPage, this.pageSize)
   //    afterDispatch(this.currentPage, this.pageSize).then((res) => {
   //      if (res.code == 200) {
   //        this.loading = false;
   //        this.total = res.data.total;
   //        this.tableData = res.data.afterSalesVoList.map((item,index) =>{
			// 	item.i = (this.currentPage - 1) * this.pageSize + index + 1;
			// 	return item;
			// });
		 //  console.log("table=>",this.tableData)
   //        //将图片地址放入数组,需要遍历循环加入数组
   //        //   for (let i = 0; i < res.data.devicesVoList.length; i++) {
   //        //     this.srcList.push(res.data.devicesVoList[i].image);
   //        //   }
   //      } else {
   //        this.loading = false;
   //        this.$message("无记录");
   //      }
   //    });
    },
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getAllGoods();
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage;
      this.getAllGoods();
    },
	// 展示零件列表
	partsOpen(row){
		row.goodsList.forEach((part,index) =>{
			part.i = index +1
		})
		this.selectData = row;
		this.selectTitle = row.name;
		this.partsShow = true;
	},
	// 关闭零件列表
	partsClose(){
		this.selectData = {}
		this.selectTitle = ""
	},
	// 远程搜索
	getUserList(query) {
		this.selectLoading = true;
		const data = {
			nickName: query,
			roleId: 7,
		}
		userApi.fuzzyQuery(data).then(res => {
			if (res.code === 200) {
				this.userList = res.data.userVoList.map(item => {
					item.label = `${item.nickName}(${item.empno})`
					return item;
				})
				this.selectLoading = false;
			}
		})
	},
  },
};
</script>

<style scoped>
.page {
  text-align: center;
}

.nameBox {
  overflow: auto; /* 显示滚动条 */
  z-index: 99;
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  width: 205px;
  height: 170px;
  border-radius: 5px;
  background-color: #ffffff;
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
  position: absolute;
}

.after-dispatch{
	height: 100%;
}

.goods-table {
  height: 94%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-top: 10px;
}
.imgUrl {
  width: 100px;
  height: 100px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
.htimg {
  width: 150px;
  height: 150px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
</style>
